package edu.zjucst.spb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import edu.zjucst.spb.dao.branch.BranchDao;
import edu.zjucst.spb.domain.entity.Branch;
import edu.zjucst.spb.service.BranchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class BranchServiceImpl implements BranchService {
    @Autowired
    private BranchDao branchDao;

    @Override
    @Transactional
    public int addBranch(Branch branch) {
        return branchDao.insert(branch);
    }
//    查询全部支部信息
    @Override
    public List<Branch> findAllBranch() {
        return branchDao.selectList(null);
    }

    @Override
    @Transactional
    public int deleteBranch(Long branchId) {
        return branchDao.delete(new LambdaQueryWrapper<Branch>()
            .eq(Branch::getId, branchId));
    }

    @Override
    @Transactional
    public int deleteBranches(List<Long> idList) {
        int cnt = 0;
        for (Long branchId : idList) {
            cnt += branchDao.delete(new LambdaQueryWrapper<Branch>()
                .eq(Branch::getId, branchId));
        }
        return cnt;
    }

    @Override
    @Transactional
    public int updateBranch(Branch branch) {
        return branchDao.update(branch, new LambdaUpdateWrapper<Branch>()
            .eq(Branch::getId, branch.getId()));
    }

    @Override
    @Transactional
    public int updateBranches(List<Branch> branchList) {
        int cnt = 0;
        for (Branch branch : branchList) {
            cnt += branchDao.update(branch, new LambdaUpdateWrapper<Branch>()
                .eq(Branch::getId, branch.getId()));
        }
        return cnt;
    }

    @Override
    @Transactional
    public List<Branch> findBranch(Branch branch) {
        return branchDao.selectList(new LambdaQueryWrapper<Branch>()
            .eq(!ObjectUtils.isEmpty(branch.getId()), Branch::getId, branch.getId())
            .eq(!ObjectUtils.isEmpty(branch.getBranchName()), Branch::getBranchName, branch.getBranchName())
        );
    }

    @Override
    public Branch findBranchById(Long Id) {
        return branchDao.selectOne(new LambdaQueryWrapper<Branch>()
            .eq(Branch::getId,Id)
        );
    }
    //    根据支部名查询支部
    @Override
    public List<Branch> findBranchByName(String branchName) {
        return branchDao.selectList(new LambdaQueryWrapper<Branch>()
            .eq(Branch::getBranchName,branchName)
        );
    }
}
